<template>
  <view class="appointment-container">
    <!-- 顶部步骤指示器 -->
    <view class="steps-indicator">
      <view :class="['step-item', { 'active': currentStep === 1 }]" @tap="goToStep(1)">
        <text class="step-number">1</text>
        <text class="step-text">选择医院</text>
      </view>
      <view class="step-separator"></view>
      <view :class="['step-item', { 'active': currentStep === 2 }]" @tap="goToStep(2)">
        <text class="step-number">2</text>
        <text class="step-text">选择科室</text>
      </view>
      <view class="step-separator"></view>
      <view :class="['step-item', { 'active': currentStep === 3 }]" @tap="goToStep(3)">
        <text class="step-number">3</text>
        <text class="step-text">选择医生</text>
      </view>
      <view class="step-separator"></view>
      <view :class="['step-item', { 'active': currentStep === 4 }]" @tap="goToStep(4)">
        <text class="step-number">4</text>
        <text class="step-text">选择时间</text>
      </view>
    </view>

    <!-- 主内容区域 - 根据步骤切换显示 -->
    <scroll-view scroll-y class="main-content-scroll">
      <!-- 步骤1: 选择医院 -->
      <view v-if="currentStep === 1" class="step-section">
        <view class="section-title">选择医院</view>
        <!-- 医院选择区域 -->
        <view class="hospital-selection">
          <view :class="['hospital-card', { 'selected': selectedHospital && selectedHospital.id === hospital.id }]"
                v-for="hospital in hospitals" :key="hospital.id">
            <view class="card-content" @tap="selectHospital(hospital)">
              <view class="card-header">
                <text class="hospital-name">{{ hospital.name }}</text>
                <text class="hospital-grade">{{ hospital.hospitalGrade }}</text>
              </view>
              <view class="card-body">
                <text class="hospital-address">{{ hospital.address }}</text>
                <view class="tags">
                  <text class="tag" v-for="tag in hospital.tags" :key="tag">{{ tag }}</text>
                </view>
              </view>
            </view>
            <view class="card-actions">
              <button class="detail-btn" @tap="goToHospitalDetail(hospital.id)">查看详情</button>
            </view>
          </view>
          <view v-if="hospitals.length === 0" class="no-results">
            <text>暂无医院信息</text>
          </view>
        </view>
        <button class="next-step-btn" @tap="nextStep" :disabled="!selectedHospital">下一步</button>
      </view>

      <!-- 步骤2: 选择科室 -->
      <view v-if="currentStep === 2" class="step-section">
        <view class="section-title">选择科室</view>
        <!-- 科室导航系统 -->
        <view class="department-grid">
          <view :class="['department-item', { 'selected': selectedDepartment && selectedDepartment.id === dept.id }]"
                v-for="dept in departments" :key="dept.id" @tap="selectDepartment(dept)">
            <view class="icon-wrapper">
              <!-- 请确保您的项目中已配置 iconfont 或其他图标资源，并有对应科室的图标类名 -->
              <text :class="'iconfont icon-' + getDepartmentIcon(dept.name)"></text>
            </view>
            <text class="dept-name">{{ dept.name }}</text>
          </view>
          <view v-if="departments.length === 0" class="no-results">
            <text>暂无科室信息</text>
          </view>
        </view>
        <button class="next-step-btn" @tap="nextStep" :disabled="!selectedDepartment">下一步</button>
        <button class="prev-step-btn" @tap="prevStep">上一步</button>
      </view>

      <!-- 步骤3: 选择医生 -->
      <view v-if="currentStep === 3" class="step-section">
        <view class="section-title">选择医生</view>
        <!-- 医生列表展示 -->
        <view class="doctor-list">
          <view :class="['doctor-card', { 'selected': selectedDoctor && selectedDoctor.id === doctor.id }]"
                v-for="doctor in sortedDoctors" :key="doctor.id" @tap="selectDoctor(doctor)">
            <image class="doctor-avatar" :src="doctor.avatar || '/static/images/default_avatar.png'"></image>
            <view class="doctor-info">
              <text class="doctor-name">{{ doctor.name }}</text>
              <text class="doctor-title">{{ doctor.jobTitle }}</text>
              <text class="doctor-specialty">{{ doctor.professionalExpertise }}</text>
            </view>
            <view class="doctor-availability">
              <text class="availability-status">{{ getDoctorAvailability(doctor) }}</text>
            </view>
          </view>
          <view v-if="doctors.length === 0" class="no-results">
            <text>暂无医生信息</text>
          </view>
        </view>
        <button class="next-step-btn" @tap="nextStep" :disabled="!selectedDoctor">下一步</button>
        <button class="prev-step-btn" @tap="prevStep">上一步</button>
      </view>

      <!-- 步骤4: 选择时间 -->
      <view v-if="currentStep === 4" class="step-section">
        <view class="section-title">选择时间</view>
        <!-- 时间选择功能 - 日历视图 -->
        <view class="calendar-view">
          <view class="calendar-header">
            <button class="icon-arrow" @tap="changeMonth(-1)">&#8592;</button>
            <text class="current-month">{{ displayYear }}年{{ displayMonth.toString().padStart(2, '0') }}月</text>
            <button class="icon-arrow" @tap="changeMonth(1)">&#8594;</button>
          </view>
          <view class="weekdays">
            <text>日</text>
            <text>一</text>
            <text>二</text>
            <text>三</text>
            <text>四</text>
            <text>五</text>
            <text>六</text>
          </view>
          <view class="dates-grid">
            <text v-for="(dateItem, index) in calendarDates" :key="index"
                  :class="['date-item', { 'today': dateItem.isToday, 'selected': selectedDate === dateItem.date, 'isPlaceholder': dateItem.isPlaceholder }]"
                  @tap="selectDate(dateItem.date)">
              {{ dateItem.isPlaceholder ? '' : new Date(dateItem.date).getDate() }}
            </text>
          </view>
        </view>
        <view class="time-slot-selection">
          <view :class="['time-slot-item', { 'selected': selectedSlotId === slot.slotId, 'disabled': Number(slot.bookedCount) >= Number(slot.totalCapacity) || slot.isActive === 0 }]"
                v-for="(slot, index) in availableSlots" :key="slot.slotId" @tap="selectTimeSlot(slot)">
            <text>{{ slot.time_slot }}</text>
            <text>{{ slot.displayStatus }}</text>
          </view>
          <view v-if="availableSlots.length === 0 && selectedDate" class="no-slots-message">
            <text>当前日期暂无可用号源，请选择其他日期。</text>
          </view>
          <view v-if="!selectedDate" class="no-slots-message">
            <text>请先选择日期以查看可用时间段。</text>
          </view>
        </view>
        <button class="next-step-btn" @tap="nextStep" :disabled="!selectedDate || !selectedSlotId">下一步</button>
        <button class="prev-step-btn" @tap="prevStep">上一步</button>
      </view>

      <!-- 步骤5: 信息确认 -->
      <view v-if="currentStep === 5" class="step-section">
        <view class="section-title">确认预约信息</view>
        <view class="confirmation-details">
          <view class="detail-item">
            <text class="label">医院:</text>
            <text class="value">{{ selectedHospital ? selectedHospital.name : '未选择' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">科室:</text>
            <text class="value">{{ selectedDepartment ? selectedDepartment.name : '未选择' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">医生:</text>
            <text class="value">{{ selectedDoctor ? selectedDoctor.name : '未选择' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">日期:</text>
            <text class="value">{{ selectedDate || '未选择' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">时间段:</text>
            <text class="value">{{ selectedTimeSlot || '未选择' }}</text>
          </view>
          <!-- 更多预约详情，例如就诊人信息等 -->
          <view class="form-item">
            <input v-model="reasonForVisit" placeholder="请输入就诊原因 (可选)" type="text" />
          </view>
        </view>
        <button class="confirm-booking-btn" @tap="confirmBooking">确认预约</button>
        <button class="prev-step-btn" @tap="prevStep">上一步</button>
      </view>

      <!-- 步骤6: 预约成功 -->
      <view v-if="currentStep === 6" class="step-section success-message">
        <text class="iconfont icon-success-fill success-icon"></text>
        <view class="success-title">预约成功！</view>
        <text class="success-text">您的预约已提交，请留意通知。</text>
        <button class="back-home-btn" @tap="backToHome">返回首页</button>
      </view>

    </scroll-view>

    <!-- 底部预约信息汇总 (固定位置) -->
    <view class="bottom-summary" v-if="currentStep < 5">
      <view class="summary-item">
        <text class="summary-label">医院:</text>
        <text class="summary-value">{{ selectedHospital ? selectedHospital.name : '待选' }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">科室:</text>
        <text class="summary-value">{{ selectedDepartment ? selectedDepartment.name : '待选' }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">医生:</text>
        <text class="summary-value">{{ selectedDoctor ? selectedDoctor.name : '待选' }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">时间:</text>
        <text class="summary-value">{{ selectedDate ? selectedDate + ' ' + selectedTimeSlot : '待选' }}</text>
      </view>
      <button class="proceed-btn" @tap="nextStep" :disabled="!canProceedToNextStep">继续</button>
    </view>
  </view>
</template>

<script>
// 导入相关接口
import { listHospital } from '@/api/hospital.js';
import { selectDepartmentByHospitalId, selectDepartmentAll } from '@/api/department.js';
import { selectDoctorByDepartmentId } from '@/api/doctor.js';
import { listSlot, addSlot } from '@/api/slot.js'; // addSlot 主要是为了模拟数据，实际预约会用 appointment
import { addAppointment } from '@/api/appointment.js';
import config from '@/config.js'; // 用于图片路径等

export default {
  data() {
    const today = new Date();
    return {
      currentStep: 1, // 当前步骤，1-4
      hospitals: [],
      departments: [],
      doctors: [],
      availableSlots: [], // 医生的可用号源列表

      selectedHospital: null,
      selectedDepartment: null,
      selectedDoctor: null,
      selectedDate: '', // 格式 YYYY-MM-DD
      selectedTimeSlot: '', // 格式 HH:mm-HH:mm
      selectedSlotId: null, // 最终确定的号源ID

      reasonForVisit: '', // 就诊原因
      imgurl: config.staticUrl, // 静态资源URL

      // 日历相关数据
      displayYear: today.getFullYear(),
      displayMonth: today.getMonth() + 1, // 月份从1开始

      // 记录上次加载的ID，用于优化数据加载
      lastFetchedHospitalId: null,
      lastFetchedDepartmentId: null,
    };
  },
  computed: {
    canProceedToNextStep() {
      switch (this.currentStep) {
        case 1:
          return !!this.selectedHospital;
        case 2:
          return !!this.selectedDepartment;
        case 3:
          return !!this.selectedDoctor;
        case 4:
          // 确保不仅选择了日期和时间段，而且该时间段是可用的 (未满号)
          const isSlotAvailable = this.availableSlots.some(slot => 
            slot.slotId === this.selectedSlotId && Number(slot.bookedCount) < Number(slot.totalCapacity) && slot.isActive === 1
          );
          return !!this.selectedDate && !!this.selectedSlotId && isSlotAvailable;
        default:
          return false;
      }
    },
    // 获取当月可预约的日期，标记当天
    calendarDates() {
      const year = this.displayYear;
      const month = this.displayMonth;
      const today = new Date();
      const currentFullDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;

      const firstDayOfMonth = new Date(year, month - 1, 1); // 月份从0开始
      const lastDayOfMonth = new Date(year, month, 0);
      const daysInMonth = lastDayOfMonth.getDate();

      const dates = [];
      // 填充上个月的空白
      const firstDayOfWeek = firstDayOfMonth.getDay(); // 0-6，周日是0
      for (let i = 0; i < firstDayOfWeek; i++) {
        dates.push({ date: '', isPlaceholder: true });
      }

      for (let i = 1; i <= daysInMonth; i++) {
        const dateStr = `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
        dates.push({
          date: dateStr,
          isToday: dateStr === currentFullDate,
          isPlaceholder: false
        });
      }
      return dates;
    },
    // 医生排序：按职称排序 (示例，可根据实际职称等级进行更精细的排序)
    sortedDoctors() {
      return [...this.doctors].sort((a, b) => {
        // 假设职称按字母顺序排序，或可定义一个职称等级映射来精确排序
        if (a.jobTitle < b.jobTitle) return -1;
        if (a.jobTitle > b.jobTitle) return 1;
        return 0;
      });
    }
  },
  onLoad(options) {
    this.fetchHospitals();
    // 处理再次预约传递的参数
    if (options.rebook === 'true') {
      this.handleRebookParams(options);
    }
  },
  onShow() {
    // 确保从其他页面返回时，医院数据也是最新的
    if (this.hospitals.length === 0) {
      this.fetchHospitals();
    }
  },
  methods: {
    // 步骤导航
    goToStep(step) {
      // 允许返回到之前完成的步骤 (1-5)
      if (step < this.currentStep && step >= 1 && step <= 5) {
        this.currentStep = step;
      } 
      // 允许前进到下一个未完成的步骤，但不能跳过步骤
      else if (step === this.currentStep + 1 && this.canProceedToNextStep) {
        this.currentStep = step;
      }
      // 允许点击当前步骤 (可选，这里不触发数据加载，只用于视觉反馈)
      else if (step === this.currentStep) {
        // No operation needed, but can trigger data refresh if desired
      }
      // 其他情况（例如尝试跳过步骤）不允许
      else {
        uni.showToast({
          title: '请按流程完成当前步骤',
          icon: 'none'
        });
        return; // 不执行后续加载
      }
      // 根据当前步骤加载数据
      this.loadDataForCurrentStep();
    },
    nextStep() {
      if (this.canProceedToNextStep) {
        this.currentStep++;
        this.loadDataForCurrentStep();
      } else {
        uni.showToast({
          title: '请完成当前步骤的选择',
          icon: 'none'
        });
      }
    },
    prevStep() {
      if (this.currentStep > 1 && this.currentStep <= 5) { // 避免返回到流程之外
        this.currentStep--;
        this.loadDataForCurrentStep(); // 返回上一步时也尝试加载数据，确保数据显示正确
      }
    },
    loadDataForCurrentStep() {
      if (this.currentStep === 1) {
        // 医院数据在 onLoad/onShow 时已加载，此处不重复加载
      } else if (this.currentStep === 2 && this.selectedHospital) {
        // 只有当当前选择的医院ID与上次加载科室的医院ID不一致时，才重新获取科室列表
        if (this.selectedHospital.id !== this.lastFetchedHospitalId) {
          this.departments = []; // 清空之前的科室列表
          this.selectedDepartment = null; // 清空科室选择
          this.fetchDepartments(this.selectedHospital.id);
        }
      } else if (this.currentStep === 3 && this.selectedDepartment) {
        // 只有当当前选择的科室ID与上次加载医生的科室ID不一致时，才重新获取医生列表
        if (this.selectedDepartment.id !== this.lastFetchedDepartmentId) {
          this.doctors = []; // 清空之前的医生列表
          this.selectedDoctor = null; // 清空医生选择
          this.fetchDoctors(this.selectedDepartment.id);
        }
      } else if (this.currentStep === 4 && this.selectedDoctor && this.selectedDate) {
        // 号源在 selectDate 中已加载，此处不重复加载
      }
    },

    // 步骤1: 选择医院
    async fetchHospitals() {
      console.log('index.vue: fetchHospitals 开始获取医院列表...');
      try {
        const res = await listHospital({}); // 获取所有医院列表
        console.log('index.vue: listHospital API 响应:', res);
        if (res.code === 200 && res.rows) {
          this.hospitals = res.rows.map(hosp => ({
            id: hosp.id,
            name: hosp.name,
            hospitalGrade: hosp.hospitalGrade,
            address: hosp.address,
            // 假设特色标签在 snapshot 里用逗号分隔，如果不是，需要调整后端或前端处理逻辑
            tags: hosp.snapshot ? hosp.snapshot.split('，') : [], 
            imgUrl: hosp.imgUrl // 医院图片
          }));
          console.log('Fetched Hospitals:', this.hospitals);
        }
      } catch (error) {
        console.error('获取医院列表失败:', error);
        uni.showToast({ title: '获取医院失败', icon: 'none' });
      }
    },
    selectHospital(hospital) {
      this.selectedHospital = hospital;
      // 当选择医院变化时，重置所有后续步骤的选择和数据
      this.selectedDepartment = null;
      this.departments = [];
      this.selectedDoctor = null;
      this.doctors = [];
      this.selectedDate = '';
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      this.availableSlots = [];
      this.lastFetchedHospitalId = null; // 重置，确保下次进入步骤2时会重新加载科室
      this.lastFetchedDepartmentId = null; // 重置，确保下次进入步骤3时会重新加载医生
    },
    goToHospitalDetail(hospitalId) {
      uni.navigateTo({
        url: `/pages/hospital/detail?id=${hospitalId}`
      });
    },

    // 步骤2: 选择科室
    async fetchDepartments(hospitalId) {
      console.log('index.vue: fetchDepartments 开始获取科室列表，hospitalId:', hospitalId);
      try {
        // 使用 selectDepartmentAll 获取所有科室，然后在前端过滤
        const res = await selectDepartmentAll(); // 调用获取所有科室的接口
        console.log('index.vue: selectDepartmentAll API 响应:', res);
        if (res.code === 200 && Array.isArray(res.data)) {
          const filteredDepartments = res.data.filter(dept => String(dept.hospitalId) === String(hospitalId));
          this.departments = filteredDepartments.map(dept => ({
            id: dept.id,
            name: dept.name,
            hospitalId: hospitalId,
          }));
          this.lastFetchedHospitalId = hospitalId;
          console.log('Filtered Departments for hospital:', this.departments);
          if (this.departments.length === 0) {
            uni.showToast({ title: '该医院暂无科室信息', icon: 'none' });
          }
        } else {
          this.departments = [];
          uni.showToast({ title: '获取科室失败或无数据', icon: 'none' });
        }
      } catch (error) {
        console.error('获取科室列表失败:', error);
        this.departments = [];
        uni.showToast({ title: '获取科室失败', icon: 'none' });
      }
    },
    selectDepartment(dept) {
      this.selectedDepartment = dept;
      // 当选择科室变化时，重置所有后续步骤的选择和数据
      this.selectedDoctor = null;
      this.doctors = [];
      this.selectedDate = '';
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      this.availableSlots = [];
      this.lastFetchedDepartmentId = null; // 重置，确保下次进入步骤3时会重新加载医生
    },

    // 获取科室图标
    getDepartmentIcon(departmentName) {
      // 您需要根据实际的 iconfont 字体库或图片资源来映射科室图标
      // 例如，如果您的 iconfont 中有 'icon-neike', 'icon-waike' 等
      const iconMap = {
        '内科': 'neike',
        '外科': 'waike',
        '儿科': 'erke',
        '妇产科': 'fuchanke',
        '眼科': 'yanke',
        '耳鼻喉科': 'erbihouke',
        '心血管中心': 'xinxueguan',
        '神经内科': 'shenjingneike',
        '呼吸内科': 'huxineike',
        '肿瘤科': 'zhongliuke',
        // ... 更多科室与图标的映射
        'default-department': 'default-department-icon' // 确保有一个默认图标，并将其添加到 iconfont 中
      };
      return iconMap[departmentName] || 'default-department'; // 默认图标类名
    },

    // 步骤3: 选择医生
    async fetchDoctors(departmentId) {
      console.log('index.vue: fetchDoctors 开始获取医生列表，departmentId:', departmentId);
      try {
        const res = await selectDoctorByDepartmentId(departmentId);
        console.log('index.vue: selectDoctorByDepartmentId API 响应:', res);
        if (res.code === 200 && res.data) {
          this.doctors = res.data.map(doc => ({
            id: doc.id,
            name: doc.name,
            jobTitle: doc.jobTitle,
            professionalExpertise: doc.professionalExpertise,
            avatar: doc.imgUrl ? this.imgurl + doc.imgUrl : '/static/images/default_avatar.png',
            departmentId: departmentId, // 补充 departmentId 便于后续判断
          }));
          this.lastFetchedDepartmentId = departmentId; // 记录本次加载的科室ID
          console.log('Fetched Doctors:', this.doctors);
        }
      } catch (error) {
        console.error('获取医生列表失败:', error);
        uni.showToast({ title: '获取医生失败', icon: 'none' });
      }
    },
    selectDoctor(doctor) {
      this.selectedDoctor = doctor;
      this.selectedDate = ''; // 重置后续选择
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      // 可以在这里立即获取该医生在当前日期的号源，或者在下一步骤获取
    },
    getDoctorAvailability(doctor) {
      // 对于医生列表页，仅返回通用状态。具体的号源信息在选择时间步骤加载。
      return '可预约';
    },

    // 步骤4: 选择时间
    selectDate(date) {
      if (!date) return; // 避免选择占位日期
      this.selectedDate = date;
      this.selectedTimeSlot = ''; // 重置时间段选择
      this.selectedSlotId = null;
      this.availableSlots = []; // 清空之前的号源列表，确保每次选择日期后重新加载
      this.fetchAvailableSlots(this.selectedDoctor.id, this.selectedDate);
    },
    async fetchAvailableSlots(doctorId, date) {
      console.log('index.vue: fetchAvailableSlots 开始获取号源，doctorId:', doctorId, 'date:', date);
      if (!doctorId || !date) {
        console.log('index.vue: fetchAvailableSlots: 缺少 doctorId 或 date.', { doctorId, date });
        return;
      }
      try {
        const query = {
          doctorId: doctorId,
          scheduleDate: date,
          departmentId: this.selectedDepartment ? this.selectedDepartment.id : null,
          hospitalId: this.selectedHospital ? this.selectedHospital.id : null,
        };
        console.log('Fetching available slots with query:', query);
        const res = await listSlot(query);
        console.log('listSlot API response:', res);
        if (res.code === 200 && res.rows) {
          this.availableSlots = res.rows.map(slot => {
            const booked = Number(slot.bookedCount);
            const total = Number(slot.totalCapacity);
            const active = Number(slot.isActive);
            let displayStatusText = '';

            if (active === 0) {
              displayStatusText = ' (不可用)';
            } else if (booked < total) {
              displayStatusText = ` (余 ${total - booked})`;
            } else {
              displayStatusText = ' (已满)';
            }

            return {
              ...slot,
              bookedCount: booked,
              totalCapacity: total,
              isActive: active,
              displayStatus: displayStatusText
            };
          });
          console.log('Fetched Available Slots (processed and type-converted):', this.availableSlots);
        } else {
          this.availableSlots = [];
          uni.showToast({ title: res.msg || '暂无可用号源', icon: 'none' });
        }
      } catch (error) {
        console.error('获取可用号源失败:', error);
        this.availableSlots = [];
        uni.showToast({ title: '获取号源失败', icon: 'none' });
      }
    },
    selectTimeSlot(slot) {
      console.log('selectTimeSlot called with slot:', slot); // 新增日志
      if (slot.isActive === 1 && Number(slot.bookedCount) < Number(slot.totalCapacity)) {
        this.selectedTimeSlot = slot.timeSlot; // 使用 slot.timeSlot 确保与后端字段名一致
        this.selectedSlotId = slot.slotId;
        console.log('selectTimeSlot: Selected Time Slot:', this.selectedTimeSlot, 'Selected Slot ID:', this.selectedSlotId);
      } else if (slot.isActive === 0) {
        uni.showToast({ title: '该时间段不可用，请选择其他时间', icon: 'none' });
        this.selectedTimeSlot = ''; // 清空选择
        this.selectedSlotId = null; // 清空选择
      } else {
        uni.showToast({ title: '该时间段已满，请选择其他时间', icon: 'none' });
        this.selectedTimeSlot = ''; // 清空选择
        this.selectedSlotId = null; // 清空选择
      }
      this.$forceUpdate(); // 强制更新视图
    },
    // 日历月份切换
    changeMonth(offset) {
      let newMonth = this.displayMonth + offset;
      let newYear = this.displayYear;

      if (newMonth > 12) {
        newMonth = 1;
        newYear++;
      } else if (newMonth < 1) {
        newMonth = 12;
        newYear--;
      }
      this.displayMonth = newMonth;
      this.displayYear = newYear;
      // 月份切换后清空日期和时间段选择，重新加载号源 (可选，如果希望切换月份后自动加载)
      this.selectedDate = '';
      this.selectedTimeSlot = '';
      this.selectedSlotId = null;
      this.availableSlots = [];
    },

    // 步骤5: 确认预约
    async confirmBooking() {
      if (!this.selectedHospital || !this.selectedDepartment || !this.selectedDoctor || !this.selectedDate || !this.selectedTimeSlot || !this.selectedSlotId) {
        uni.showToast({ title: '请完善预约信息', icon: 'none' });
        return;
      }

      const bookingData = {
        userId: uni.getStorageSync('userId') || 0, // 假设用户ID从缓存获取或登录后获得
        slotId: this.selectedSlotId,
        hospitalId: this.selectedHospital.id,
        departmentId: this.selectedDepartment.id,
        doctorId: this.selectedDoctor.id,
        appointmentDate: this.selectedDate,
        appointmentTimeSlot: this.selectedTimeSlot,
        status: '待确认', // 初始状态
        reasonForVisit: this.reasonForVisit,
        // contactPersonName: '', // 如果有代约人功能，这里需要用户输入
        // contactPersonPhone: '',
      };

      try {
        const res = await addAppointment(bookingData);
        if (res.code === 200) {
          uni.showToast({ title: '预约成功', icon: 'success' });
          this.currentStep = 6; // 跳转到成功页面
        } else {
          uni.showToast({ title: res.msg || '预约失败', icon: 'none' });
        }
      } catch (error) {
        console.error('预约失败:', error);
        uni.showToast({ title: '预约请求失败', icon: 'none' });
      }
    },
    backToHome() {
      uni.switchTab({
        url: '/pages/index/index' // 返回首页
      });
    },
    async handleRebookParams(options) {
      console.log('index.vue: handleRebookParams 开始处理再次预约参数:', options);
      try {
        // 1. 设置医院
        if (options.hospitalId) {
          console.log('index.vue: handleRebookParams: 正在设置医院...');
          const hospitalRes = await listHospital({ id: options.hospitalId });
          console.log('index.vue: handleRebookParams: listHospital 响应:', hospitalRes);
          if (hospitalRes.code === 200 && hospitalRes.rows && hospitalRes.rows.length > 0) {
            this.selectedHospital = {
              id: hospitalRes.rows[0].id,
              name: hospitalRes.rows[0].name,
              hospitalGrade: hospitalRes.rows[0].hospitalGrade,
              address: hospitalRes.rows[0].address,
              tags: hospitalRes.rows[0].snapshot ? hospitalRes.rows[0].snapshot.split('，') : [],
              imgUrl: hospitalRes.rows[0].imgUrl
            };
            this.currentStep = 2; // 自动跳转到选择科室
            console.log('index.vue: handleRebookParams: 医院设置成功，跳转到步骤2');
          } else {
            console.log('index.vue: handleRebookParams: 未找到指定医院或API错误', hospitalRes);
          }
        }

        // 2. 设置科室 (依赖于医院已选择)
        if (options.departmentId && this.selectedHospital) {
          console.log('index.vue: handleRebookParams: 正在设置科室...');
          await this.fetchDepartments(this.selectedHospital.id); // 确保科室列表已加载
          const department = this.departments.find(dept => String(dept.id) === String(options.departmentId));
          if (department) {
            this.selectedDepartment = department;
            this.currentStep = 3; // 自动跳转到选择医生
            console.log('index.vue: handleRebookParams: 科室设置成功，跳转到步骤3');
          } else {
            console.log('index.vue: handleRebookParams: 未找到指定科室', options.departmentId);
          }
        }

        // 3. 设置医生 (依赖于科室已选择)
        if (options.doctorId && this.selectedDepartment) {
          console.log('index.vue: handleRebookParams: 正在设置医生...');
          await this.fetchDoctors(this.selectedDepartment.id); // 确保医生列表已加载
          const doctor = this.doctors.find(doc => String(doc.id) === String(options.doctorId));
          if (doctor) {
            this.selectedDoctor = doctor;
            this.currentStep = 4; // 自动跳转到选择时间
            console.log('index.vue: handleRebookParams: 医生设置成功，跳转到步骤4');
            // 默认选择今天的日期，并加载号源
            const today = new Date();
            this.displayYear = today.getFullYear();
            this.displayMonth = today.getMonth() + 1;
            this.selectedDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
            console.log('index.vue: handleRebookParams: 准备加载号源，默认日期:', this.selectedDate);
            await this.fetchAvailableSlots(this.selectedDoctor.id, this.selectedDate);
            console.log('index.vue: handleRebookParams: 号源加载完成');
          } else {
            console.log('index.vue: handleRebookParams: 未找到指定医生', options.doctorId);
          }
        }

        // 确保 UI 更新
        this.$forceUpdate();
        console.log('index.vue: handleRebookParams 处理完成。');

      } catch (error) {
        console.error('index.vue: 处理再次预约参数失败:', error);
        uni.showToast({
          title: '预加载信息失败，请手动选择',
          icon: 'none'
        });
      }
    },
  }
};
</script>

<style scoped>
/* 整体容器 */
.appointment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部步骤指示器 */
.steps-indicator {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background: linear-gradient(to right, #1E90FF, #1E90FF); /* 渐变头部设计 */
  color: #fff;
  font-size: 28rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  text-align: center;
  opacity: 0.6; /* 未激活步骤透明度 */
  transition: opacity 0.3s ease;
}

.step-item.active {
  opacity: 1;
  font-weight: bold;
}

.step-number {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8rpx;
  font-size: 24rpx;
}

.step-item.active .step-number {
  background-color: #fff;
  color: #4B7BFF;
}

.step-separator {
  width: 80rpx;
  height: 2rpx;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 0 10rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
}

/* 主内容滚动区域 */
.main-content-scroll {
  flex: 1;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
}

.step-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  text-align: center;
  flex-shrink: 0;
}

/* 医院选择 */
.hospital-selection {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.hospital-card {
  background-color: #f9f9f9;
  border-radius: 16rpx;
  padding: 30rpx;
  border: 2rpx solid #eee;
  transition: all 0.2s ease;
}

.hospital-card.selected {
  border-color: #4B7BFF;
  box-shadow: 0 0 15rpx rgba(75, 123, 255, 0.3);
  background-color: #e6f0ff; /* 浅蓝色背景 */
}

.card-content {
  flex: 1; /* 占据剩余空间 */
  padding-right: 20rpx; /* 与按钮的间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.hospital-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.hospital-grade {
  background-color: #1E90FF;
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.hospital-address {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.tag {
  background-color: #E0F7FA;
  color: #00BCD4;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
}

.card-actions {
  display: flex;
  align-items: center;
}

.detail-btn {
  background-color: #00BCD4; /* 青色按钮 */
  color: #fff;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  line-height: 1; /* 确保文本垂直居中 */
}

/* 科室导航 */
.department-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  text-align: center;
}

.department-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 10rpx;
  border-radius: 16rpx;
  border: 2rpx solid #eee;
  background-color: #f9f9f9;
  transition: all 0.2s ease;
}

.department-item.selected {
  border-color: #4B7BFF;
  box-shadow: 0 0 15rpx rgba(75, 123, 255, 0.3);
  background-color: #e6f0ff;
}

.icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  background-color: #cceeff; /* 占位背景色 */
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15rpx;
  font-size: 48rpx; /* 图标大小 */
  color: #4B7BFF; /* 图标颜色 */
}

.dept-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

/* 医生列表 */
.doctor-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.doctor-card {
  display: flex;
  align-items: center;
  background-color: #f9f9f9;
  border-radius: 16rpx;
  padding: 30rpx;
  border: 2rpx solid #eee;
  transition: all 0.2s ease;
}

.doctor-card.selected {
  border-color: #4B7BFF;
  box-shadow: 0 0 15rpx rgba(75, 123, 255, 0.3);
  background-color: #e6f0ff;
}

.doctor-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
  object-fit: cover;
  flex-shrink: 0;
}

.doctor-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.doctor-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.doctor-title {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.doctor-specialty {
  font-size: 24rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.doctor-availability {
  margin-left: 20rpx;
  padding: 10rpx 20rpx;
  border-radius: 12rpx;
  background-color: #28a745; /* 有号绿色 */
  color: #fff;
  font-size: 24rpx;
  flex-shrink: 0;
}

/* 时间选择 */
.calendar-view {
  background-color: #f0f8ff; /* 浅蓝色背景 */
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  text-align: center;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.calendar-header .icon-arrow {
  font-size: 40rpx;
  color: #4B7BFF;
  padding: 10rpx;
}

.current-month {
  flex: 1;
  text-align: center;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
  margin-bottom: 15rpx;
  font-size: 26rpx;
  color: #999;
}

.dates-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
}

.date-item {
  width: 70rpx; /* 固定宽度 */
  height: 70rpx; /* 固定高度 */
  line-height: 70rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  transition: all 0.2s ease;
}

.date-item.today {
  border: 2rpx solid #4B7BFF;
  color: #4B7BFF;
  font-weight: bold;
}

.date-item.selected {
  background-color: #4B7BFF;
  color: #fff;
}

.date-item.isPlaceholder {
  background-color: transparent;
  color: #ccc;
  pointer-events: none; /* 禁用点击事件 */
}

.no-slots-message {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 30rpx;
}

.time-slot-selection {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.time-slot-item {
  background-color: #f9f9f9;
  border: 2rpx solid #eee;
  border-radius: 16rpx;
  padding: 20rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  transition: all 0.2s ease;
}

.time-slot-item.selected {
  border-color: #4B7BFF;
  box-shadow: 0 0 15rpx rgba(75, 123, 255, 0.3);
  background-color: #e6f0ff;
}

.time-slot-item.disabled {
  background-color: #e9ecef;
  color: #999;
  border-color: #dee2e6;
  opacity: 0.7;
  cursor: not-allowed;
}

/* 确认预约 */
.confirmation-details {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}

.detail-item .label {
  font-weight: bold;
  color: #666;
  width: 120rpx;
  flex-shrink: 0;
}

.detail-item .value {
  color: #333;
  flex: 1;
}

.form-item {
  margin-top: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
}

.form-item input {
  width: 100%;
  font-size: 28rpx;
  color: #333;
}

/* 按钮样式 */
.next-step-btn, .confirm-booking-btn, .back-home-btn, .proceed-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background-color: #1E90FF;
  color: #fff;
  font-size: 32rpx;
  margin-top: 30rpx;
  text-align: center;
  transition: background-color 0.3s ease;
}

.next-step-btn:active, .confirm-booking-btn:active, .back-home-btn:active, .proceed-btn:active {
  background-color: #3a62d0;
}

.next-step-btn[disabled], .proceed-btn[disabled] {
  background-color: #a7c4ff;
  cursor: not-allowed;
}

.prev-step-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  background-color: #f0f0f0; /* 浅灰色 */
  color: #666;
  font-size: 32rpx;
  margin-top: 20rpx; /* 略小于下一步按钮的间距 */
  text-align: center;
  transition: background-color 0.3s ease;
}

.prev-step-btn:active {
  background-color: #e0e0e0;
}

/* 预约成功页面 */
.success-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  min-height: 500rpx; /* 确保有足够高度 */
}

.success-icon {
  font-size: 160rpx;
  color: #28a745; /* 绿色成功图标 */
  margin-bottom: 40rpx;
}

.success-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.success-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 60rpx;
}

/* 底部预约信息汇总 */
.bottom-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  bottom: 0;
  z-index: 9;
}

.summary-item {
  display: flex;
  flex-direction: column;
  font-size: 24rpx;
  flex: 1;
  text-align: center;
}

.summary-label {
  color: #999;
  margin-bottom: 5rpx;
}

.summary-value {
  color: #333;
  font-weight: bold;
}

.proceed-btn {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  border-radius: 35rpx;
  margin-top: 0; /* 覆盖默认margin-top */
}

/* iconfont 示例，您需要根据实际图标库调整 */
/* icon-success-fill */
</style> 